<?php
namespace Hawk\Model;
use Think\Model;
use Think\Model\RelationModel; 
class PartModel extends RelationModel 
{
	protected $insertFields = array('name','pid','is_use');
	protected $updateFields = array('id','name','pid','is_use');
	protected $_validate = array(
		array('name', 'require', '部门名称不能为空！', 1, 'regex', 3),
		array('name', 'require', '部门名称必须唯一！', 1, 'unique', 3),
	);
	/**
     * 部门分级查询
     * @author hawk <2271030162@qq.com>
     * @param  $where int
     * @return array
     */
    public function getPart($where)
    {
    	$pmodel=M('Part');
        $depart =$pmodel->where($where)->order('sort asc')->select();
        $menu = array();
        if($depart){
            foreach ($depart as $v) {
                //获取顶级数据
                if ($v['pid']==0) {
                    foreach ($depart as $v1) {
                        //获取二级数据
                        if ($v1['pid']==$v['id']) {
                            foreach ($depart as $v2) {
                                //获取三级数据
                                if ($v2['pid']==$v1['id']) {
                                    foreach($depart as $v3){
                                        //获取4级数据
                                        if($v3['pid']==$v2['id']){
                                            $v2['child'][]=$v3;
                                        }
                                    }
                                    $v1['child'][]=$v2;
                                }
                            }
                            $v['child'][]=$v1;
                        }
                    }
                    $menu[]=$v;
                }
            }
        }
        return $menu;
    }
    /**
     * 标记级数
     * @author hawk <2271030162@qq.com>
     * @param  $where int
     * @return array
     */
    public function reSort($data, $parent_id=0, $level=0, $isClear=TRUE)
	{
		static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v)
		{
			if($v['pid'] == $parent_id)
			{
				$v['level'] = $level;
				$ret[] = $v;
				$this->reSort($data, $v['id'], $level+1, FALSE);
			}
		}
		return $ret;
	}
    /**
     * ID to partName
     * @author hawk <2271030162@qq.com>
     * @param  $id int
     * @return string
     */
    public function getPartName($id){
        $data = $this->find($id);
        return $data['name'];
    }
}